﻿Imports DevExpress.XtraScheduler
Imports DevExpress.XtraScheduler.TimeOfDayInterval
Imports DevExpress.Utils.Menu
Imports DevExpress.XtraEditors.Repository

Public Class frmShowAppointment
    Dim memoMessages As RepositoryItemMemoEdit
    Dim blnIsViewChanged As Boolean = False

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub

    Public Sub PopulateScheduler()
        Me.DaTblAppoinments.Connection = gconWebPlusMed
        'Me.DaTblAppoinments.Fill(Me.DsAppointments.dtTblAppoinments)
        If gintUserLevelId <= 2 Then
            If gintUserLevelId = 2 Then
                DaTblAppoinments.Adapter.SelectCommand.CommandText = "SELECT tblAppointments.AppointmentId, tblAppointments.DoctorId, tblAppointments.PatientId, tblAppointments.AppointmentDateTime, DATEADD(Minute, " & _
                     "tblAppointments.AppointmentDuration, tblAppointments.AppointmentDateTime) AS [End Time], tblAppointments.Description, tblAppointments.Notes, " & _
                     "tblPatientInfo.PatientTitle + ' ' + (IsNull(tblPatientInfo.LastName + ', ' , '') + tblPatientInfo.FirstName + Isnull(' ' + tblPatientInfo.MiddleName, '') ) AS [Patient Name] " & _
                     "FROM tblAppointments INNER JOIN " & _
                     "tblPatientInfo ON tblAppointments.PatientId = tblPatientInfo.PatientId  And tblAppointments.DoctorId=" & gintUserID & _
               IIf(blnIsViewChanged = False, " Where tblAppointments.AppointmentDateTime Between '" & Format(gdtCurrentDate, "MM/dd/yyyy 00:01") & "' And '" & Format(gdtCurrentDate, "MM/dd/yyyy 23:59") & "'", "")
            Else
                DaTblAppoinments.Adapter.SelectCommand.CommandText = "SELECT tblAppointments.AppointmentId, tblAppointments.DoctorId, tblAppointments.PatientId, tblAppointments.AppointmentDateTime, DATEADD(Minute, " & _
                                                "tblAppointments.AppointmentDuration, tblAppointments.AppointmentDateTime) AS [End Time], tblAppointments.Description, tblAppointments.Notes, " & _
                                                "tblPatientInfo.PatientTitle + ' ' + (IsNull(tblPatientInfo.LastName + ', ' , '') + tblPatientInfo.FirstName + Isnull(' ' + tblPatientInfo.MiddleName, '') ) AS [Patient Name] " & _
                                                "FROM tblAppointments INNER JOIN " & _
                                                "tblPatientInfo ON tblAppointments.PatientId = tblPatientInfo.PatientId" & _
                 IIf(blnIsViewChanged = False, " Where tblAppointments.AppointmentDateTime Between '" & Format(gdtCurrentDate, "MM/dd/yyyy 00:01") & "' And '" & Format(gdtCurrentDate, "MM/dd/yyyy 23:59") & "'", "")
            End If
        Else
            DaTblAppoinments.Adapter.SelectCommand.CommandText = "SELECT tblAppointments.AppointmentId, tblAppointments.DoctorId, tblAppointments.PatientId, tblAppointments.AppointmentDateTime, DATEADD(Minute, " & _
                     "tblAppointments.AppointmentDuration, tblAppointments.AppointmentDateTime) AS [End Time], tblAppointments.Description, tblAppointments.Notes, " & _
                     "tblPatientInfo.PatientTitle + ' ' + (IsNull(tblPatientInfo.LastName + ', ' , '') + tblPatientInfo.FirstName + Isnull(' ' + tblPatientInfo.MiddleName, '') ) AS [Patient Name] " & _
                     "FROM tblAppointments INNER JOIN " & _
                     "tblPatientInfo ON tblAppointments.PatientId = tblPatientInfo.PatientId  And tblAppointments.DoctorId=" & lkDoctor.EditValue & _
                     IIf(blnIsViewChanged = False, " Where tblAppointments.AppointmentDateTime Between '" & Format(gdtCurrentDate, "MM/dd/yyyy 00:01") & "' And '" & Format(gdtCurrentDate, "MM/dd/yyyy 23:59") & "'", "")

        End If

        Me.DaTblAppoinments.Fill(Me.DsAppointments.dtTblAppoinments)

        SendKeys.Send("{F5}")
    End Sub

    Public Sub PopulateTaskGrid()
        Dim dsTemp As DataSet
        Dim strQuery As String = ""
        Try
            'If gintUserLevelId < 2 Then
            '    strQuery = "SELECT TaskID [record_id],TaskDesc,DueDate,Priority FROM tblTasks WHERE ForUser=" & gintUserID & " AND " & _
            '           "Completed=0 AND DueDate='" & Format(dtGetServerDate, gstrDtFormat) & "'"
            'Else
            '    If IsDBNullOrNothing(lkDoctor.EditValue) Then
            '        strQuery = "SELECT TaskID [record_id],TaskDesc,DueDate,Priority FROM tblTasks WHERE ForUser=" & gintUserID & " AND " & _
            '          "Completed=0 AND DueDate='" & Format(dtGetServerDate, gstrDtFormat) & "'"
            '    Else
            '        strQuery = "SELECT TaskID [record_id],TaskDesc,DueDate,Priority FROM tblTasks WHERE ForUser=" & lkDoctor.EditValue & " AND " & _
            '                               "Completed=0 AND DueDate='" & Format(dtGetServerDate, gstrDtFormat) & "'"
            '    End If
            'End If

            strQuery = "SELECT TaskID [record_id],TaskDesc, " & _
                        "P.PatientTitle + ' ' + (IsNull(P.LastName + ', ' , '') + P.FirstName + Isnull(' ' + P.MiddleName, '') ) [Patient Name], " & _
                        "DueDate,Priority FROM tblTasks T LEFT JOIN tblPatientInfo P On T.PatientId=P.PatientId " & _
                        " WHERE ForUser=" & IIf(gintUserLevelId < 2, gintUserID, IIf(IsDBNullOrNothing(lkDoctor.EditValue), gintUserID, lkDoctor.EditValue)) & " AND " & _
                        " Completed=0 AND DueDate='" & Format(dtGetServerDate, gstrDtFormat) & "'"

            dsTemp = FillDataSet(strQuery)
            With grdTask
                .BeginUpdate()
                .DataSource = dsTemp.Tables(0)
                .EndUpdate()
                .ForceInitialize()
            End With
            With gdvTask
                'Primary Key Field
                .Columns("record_id").Visible = False
                .Columns("record_id").OptionsColumn.ShowInCustomizationForm = False
            End With
        Catch ex As Exception

        End Try
    End Sub

    Public Sub PopulatePatientWaitingGrid()
        'FillPatientWatingGrid
        Dim Status As Integer
        Dim strQuery As String = ""
        Dim dsTemp As DataSet
        If gintUserLevelId = 1 OrElse gintUserLevelId = 2 OrElse gintUserLevelId <> 3 Then
            Status = PatientStatus.AwaitingDoctor
        ElseIf gintUserLevelId = 3 Then
            Status = PatientStatus.AwaitingNurse
        End If

        If gintUserLevelId <> 4 Then
            strQuery = "SELECT tblVisits.VisitId [VisitId],tblPatientInfo.PatientId [PatientId] ,tblPatientInfo.PatientTitle + ' ' + (IsNull(tblPatientInfo.LastName + ', ' , '') + tblPatientInfo.FirstName + Isnull(' ' + tblPatientInfo.MiddleName, '') ) AS Name, " & _
                                 "AppointmentType,VisitDate as ArrivalTime, " & _
                                 "LtblPatientStatus.PatientStatus as [Patient Status] FROM (tblPatientInfo INNER JOIN " & _
                                 "(tblVisits JOIN LtblAppointmentType ON tblVisits.AppointmentTypeId=LtblAppointmentType.AppointmentTypeId) " & _
                                 "ON tblPatientInfo.PatientId = tblVisits.PatientId) INNER JOIN LtblPatientStatus ON " & _
                                 "tblVisits.PatientStatusID=LtblPatientStatus.PatientStatusID Where tblVisits.PatientStatusID <>" & PatientStatus.VisitComplete & " and VisitDate " & _
                                 "Between '" & CDate(Today).ToShortDateString & " 00:00' and '" & CDate(Today).ToShortDateString & " 23:59' "
        ElseIf gintUserLevelId = 4 Then
            strQuery = "Select V.VisitId [VisitId],P.PatientId [PatientId],P.PatientTitle + ' ' + (IsNull(P.LastName + ', ' , '') + P.FirstName + Isnull(' ' + P.MiddleName, '') ) AS [Name]," & _
                                     "AppointmentType,VisitDate as ArrivalTime, " & _
                                     "S.PatientStatus as [Patient Status],U.FirstName + IsNull(' ' + U.LastName,'') as [Doctor Name] " & _
                                     "from tblPatientInfo P,tblVisits V,LtblAppointmentType A,LtblPatientStatus S, " & _
                                     "tblUsers U,tblPracticeInfo I where V.AppointmentTypeId = A.AppointmentTypeId " & _
                                     "And P.PatientId = V.PatientId and V.PracticeId=I.PracticeId and I.UserId=U.UserId " & _
                                     "and V.PatientStatusID <>" & PatientStatus.VisitComplete & " and V.PatientStatusID=S.PatientStatusID and VisitDate Between '" & CDate(Today).ToShortDateString & " 00:00' and '" & CDate(Today).ToShortDateString & " 23:59' "
        End If
        
        dsTemp = FillDataSet(strQuery)
        With grdPatientWaiting
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With
        With gdvPatientWaiting
            .Columns("ArrivalTime").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
            .Columns("ArrivalTime").DisplayFormat.FormatString = "hh:mm tt"
            .Columns("VisitId").Visible = False
            .Columns("PatientId").Visible = False
        End With
        'now populate grid
    End Sub

    Public Sub SetSchedulerTime()

        Dim dayId As Integer
        dayId = Today.DayOfWeek
        ScAppointment.ActiveViewType = SchedulerViewType.Day
        Dim view As DayView = ScAppointment.ActiveView
        ScAppointment.Start = DateTime.Now
        view.TimeSlots.Clear()
        Dim dsTemp As New DataSet
        Dim dsTempInner As New DataSet
        Dim MyTime As DateTime
        Dim intDuration As Int16
        dsTemp = FillDataSet("select f.AppointmentTime[StartTime],e.AppointmentTime[EndTime],m.AppointmentDuration[Duration] From tblDayWiseAppointmentTime m,LtblFirstAppointmentTimes f,LtblLastAppointmentTimes e Where m.FirstAppointmentTimeId=f.AppointmentTimeId And m.LastAppointmentTimeId=e.AppointmentTimeId And m.UserId=" & _
                             IIf(gintUserLevelId < 2, gintUserID, IIf(IsDBNullOrNothing(lkDoctor.EditValue), gintUserID, lkDoctor.EditValue)) & " and m.DayId=" & dayId)
        If dsTemp.Tables(0).Rows.Count > 0 Then
            intDuration = dsTemp.Tables(0).Rows(0).Item("Duration")
            ScAppointment.DayView.TimeSlots.Add(New TimeSlot(TimeSpan.FromMinutes(intDuration), intDuration & "min"))
            view.TimeRulers(0).ShowMinutes = True
            MyTime = dsTemp.Tables(0).Rows(0).Item("StartTime")
            view.VisibleTime.Start = New TimeSpan(MyTime.Hour, 0, 0)
            MyTime = dsTemp.Tables(0).Rows(0).Item("EndTime")
            view.VisibleTime.End = New TimeSpan(MyTime.Hour, 0, 0)
        Else
            dsTempInner = FillDataSet("Select f.AppointmentTime[StartTime],e.AppointmentTime[EndTime],m.AppointmentDuration[Duration] From tblPracticeInfo m,LtblFirstAppointmentTimes f,LtblLastAppointmentTimes e Where m.FirstAppointmentTimeId=f.AppointmentTimeId And m.LastAppointmentTimeId=e.AppointmentTimeId And m.UserId=" & _
                                     IIf(gintUserLevelId < 2, gintUserID, IIf(IsDBNullOrNothing(lkDoctor.EditValue), gintUserID, lkDoctor.EditValue)))
            If dsTempInner.Tables(0).Rows.Count > 0 Then
                intDuration = dsTempInner.Tables(0).Rows(0).Item("Duration")
                ScAppointment.DayView.TimeSlots.Add(New TimeSlot(TimeSpan.FromMinutes(intDuration), intDuration & "min"))

                view.TimeRulers(0).ShowMinutes = True
                MyTime = dsTempInner.Tables(0).Rows(0).Item("StartTime")
                view.VisibleTime.Start = New TimeSpan(MyTime.Hour, 0, 0)
                MyTime = dsTempInner.Tables(0).Rows(0).Item("EndTime")
                view.VisibleTime.End = New TimeSpan(MyTime.Hour, 0, 0)
            End If
        End If

        dsTempInner.Dispose()
        dsTemp.Dispose()
    End Sub

    Private Sub frmShowAppointment_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Call btnRefresh_OpenLink(Nothing, Nothing)
        If gdvMessageWaiting.RowCount = 0 Then
            MenuDelete.Enabled = False
        Else
            MenuDelete.Enabled = True
        End If
        If Array.IndexOf(gstrAPForms, "frmNurseNote", 0) >= 0 Then
            MnuNurseNotes.Enabled = True
        Else
            MnuNurseNotes.Enabled = False
        End If
        If Array.IndexOf(gstrAPForms, "frmDoctorsNote", 0) >= 0 Then
            MnuDoctorNotes.Enabled = True
        Else
            MnuDoctorNotes.Enabled = False
        End If
        If Array.IndexOf(gstrAPForms, "frmChargeAndPayment", 0) >= 0 Then
            MnuChargesAndPayment.Enabled = True
        Else
            MnuChargesAndPayment.Enabled = False
        End If
    End Sub
    Private Sub frmShowAppointment_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Call SetImageControl(Me)
        Me.DaTblAppoinments.Connection = gconWebPlusMed
        Me.DaTblAppoinments.Fill(Me.DsAppointments.dtTblAppoinments)
        Call PopulateTaskGrid()
        Call PopulatePatientWaitingGrid()
        gstrUserAddress1 = strRecordID("tblPracticeInfo", "Address1", "UserId=" & gintUserID)
        lblUserName.Text = gstrUserName
        lblUserAddress.Text = IIf(gstrUserAddress1 = "Null", "", gstrUserAddress1)
        Call SetSchedulerTime()
        lblDate.Text = Today.DayOfWeek.ToString & " " & Format(DateTime.Now, "MMMM dd yyyy")
        lkDoctor.SendToBack()
        If gintUserLevelId > 2 Then
            'lcItemDoctorLookup.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always
            lcDoctorName.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always
            'Populate Doctor LookupBox
            PopulateLookupDX(lkDoctor, "Name", "UserId", "tblPracticeInfo JOIN tblUsers ON tblPracticeInfo.UserId=tblUsers.UserId", "tblUsers.UserId,(FirstName + ' ' + LastName) as  Name", "", "Name")
            lkDoctor.ItemIndex = 0
        Else
            lcDoctorName.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never
        End If
    End Sub

    Private Sub ScAppointment_ActiveViewChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ScAppointment.ActiveViewChanged
        blnIsViewChanged = True
        Call RefreshData("Appointments")
    End Sub

    Private Sub ScAppointment_AppointmentViewInfoCustomizing(ByVal sender As Object, ByVal e As DevExpress.XtraScheduler.AppointmentViewInfoCustomizingEventArgs) Handles ScAppointment.AppointmentViewInfoCustomizing
        Dim apptPatientId As Integer = Val(strRecordID("tblAppointments", "PatientId", "AppointmentId=" & Val(e.ViewInfo.Appointment.LabelId)))
        Dim VisitPatientId As Integer = Val(strRecordID("tblVisits", "PatientId", "VisitDate between '" & Format(CDate(e.ViewInfo.Appointment.Start), gstrDtFormat & " 00:01") & "' and '" & Format(CDate(e.ViewInfo.Appointment.Start), gstrDtFormat & " 23:59") & "' and PatientId=" & apptPatientId & ""))
        If VisitPatientId > 0 Then
            e.ViewInfo.Appearance.ForeColor = Color.Red
        End If
    End Sub

    Private Sub SchedulerControl1_EditAppointmentFormShowing(ByVal sender As System.Object, ByVal e As DevExpress.XtraScheduler.AppointmentFormEventArgs) Handles ScAppointment.EditAppointmentFormShowing
        If Array.IndexOf(gstrAPForms, "frmAppointmentEntry", 0) >= 0 Then
            Dim apt As Appointment = e.Appointment

            Dim frmTempAppointmentEntry As frmAppointmentEntry = New frmAppointmentEntry()
            If ScAppointmentStorage.Appointments.IsNewAppointment(apt) Then
                frmTempAppointmentEntry.apptId = Nothing
                frmTempAppointmentEntry.SubName = Nothing
            Else
                frmTempAppointmentEntry.apptId = apt.LabelId
                frmTempAppointmentEntry.SubName = apt.Subject
            End If
            frmTempAppointmentEntry.stDate = Format(DateTime.Now, "MM/dd/yyyy")
            frmTempAppointmentEntry.stTime = DateTime.MinValue.AddTicks(apt.Start.TimeOfDay.Ticks)
            frmTempAppointmentEntry.endTime = DateTime.MinValue.AddTicks(apt.End.TimeOfDay.Ticks)
            frmTempAppointmentEntry.ShowInTaskbar = False
            e.DialogResult = frmTempAppointmentEntry.ShowDialog()
            e.Handled = True
            ScAppointment.Refresh()
        Else
            e.Handled = True
            Exit Sub
        End If

    End Sub

    Private Sub SchedulerControl1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ScAppointment.KeyDown
        If e.KeyCode = Keys.F5 Then
            Me.DaTblAppoinments.Connection = gconWebPlusMed
            Me.DaTblAppoinments.Fill(Me.DsAppointments.dtTblAppoinments)
            ' Call PopulatePatientWaitingGrid()
        End If
    End Sub


    Private Sub ScAppointment_PreparePopupMenu(ByVal sender As System.Object, ByVal e As DevExpress.XtraScheduler.PreparePopupMenuEventArgs) Handles ScAppointment.PreparePopupMenu
        If Array.IndexOf(gstrAPForms, "frmAppointmentEntry", 0) >= 0 Then
            If e.Menu.Id = SchedulerMenuItemId.AppointmentMenu Then
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.LabelSubMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.DefaultMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.StatusSubMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.RulerMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.SwitchTimeScale)
                'e.Menu.RemoveMenuItem(SchedulerMenuItemId.OpenAppointment)

            Else

                e.Menu.RemoveMenuItem(SchedulerMenuItemId.GotoToday)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.GotoDate)
                ' e.Menu.RemoveMenuItem(SchedulerMenuItemId.SwitchViewMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.LabelSubMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.AppointmentMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.DefaultMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.StatusSubMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.RulerMenu)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.NewAllDayEvent)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.NewRecurringAppointment)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.NewRecurringEvent)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.CustomizeTimeRuler)
                'e.Menu.RemoveMenuItem(SchedulerMenuItemId.CustomizeCurrentView)
                e.Menu.RemoveMenuItem(SchedulerMenuItemId.SwitchTimeScale)
            End If
        Else
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.GotoToday)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.GotoDate)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.SwitchViewMenu)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.LabelSubMenu)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.AppointmentMenu)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.DefaultMenu)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.StatusSubMenu)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.RulerMenu)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.NewAllDayEvent)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.NewRecurringAppointment)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.NewRecurringEvent)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.CustomizeTimeRuler)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.CustomizeCurrentView)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.SwitchTimeScale)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.NewAppointment)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.OpenAppointment)
            e.Menu.RemoveMenuItem(SchedulerMenuItemId.DeleteAppointment)

        End If
    End Sub

    Private Sub SchedulerStorage1_AppointmentDeleting(ByVal sender As Object, ByVal e As DevExpress.XtraScheduler.PersistentObjectCancelEventArgs) Handles ScAppointmentStorage.AppointmentDeleting
        'Dim appId As Integer = controller.LabelId
        For Each apt As Appointment In ScAppointment.SelectedAppointments
            Call DeleteFromTable("tblAppointments", "AppointmentId=" & apt.LabelId)
        Next
    End Sub

    Public Sub RefreshData(ByVal strRef As String)
        'Application.DoEvents()
        If strRef = "All" Or strRef = "Tasks" Then Call PopulateTaskGrid()
        If strRef = "All" Or strRef = "Visits" Then Call PopulatePatientWaitingGrid()
        If strRef = "All" Or strRef = "Messages" Then Call PopulateMessages()
        If strRef = "All" Or strRef = "Appointments" Then
            If blnIsViewChanged = False Then Call SetSchedulerTime()
            Call PopulateScheduler()
        End If
        blnIsViewChanged = False
        'Application.DoEvents()
    End Sub

    Private Sub PopulateMessages()
        Try
            Dim dsTemp As DataSet
            dsTemp = FillDataSet("SELECT MessageId,SenderId, " & _
                                 "P.PatientTitle + ' ' + (IsNull(P.LastName + ', ' , '') + P.FirstName + Isnull(' ' + P.MiddleName, '') ) [Patient Name], " & _
                                 "FullName [From],MessageDate [Date],Message FROM tblMessages " & _
                                 "Left join tblPatientInfo P on tblMessages.PatientId=P.PatientId  " & _
                                 "JOIN vwUserDetails ON SenderId=UserId WHERE Acknowledgement=1 AND ReceiverId=" & IIf(gintUserLevelId < 2, gintUserID, IIf(IsDBNullOrNothing(lkDoctor.EditValue), gintUserID, lkDoctor.EditValue)) & " Order By MessageDate desc")
            gdvMessageWaiting.Columns.Clear()
            memoMessages = New RepositoryItemMemoEdit
            memoMessages.Name = "Message"
            With grdMessageWaiting
                .BeginUpdate()
                .DataSource = dsTemp.Tables(0)
                .EndUpdate()
                .ForceInitialize()
            End With
            With gdvMessageWaiting
                'Primary Key Field
                .Columns("MessageId").Visible = False
                .Columns("MessageId").OptionsColumn.ShowInCustomizationForm = False
                .Columns("SenderId").Visible = False
                .Columns("SenderId").OptionsColumn.ShowInCustomizationForm = False
                .Columns("Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .Columns("Date").DisplayFormat.FormatString = gstrDtFormat & " hh:mm tt"
                .Columns("Message").ColumnEdit = memoMessages
                .ExpandAllGroups()
                .BestFitColumns()
                .OptionsView.RowAutoHeight = True
                gdvMessageWaiting.OptionsBehavior.Editable = False
            End With
            dsTemp.Dispose()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of mdlAllFunctions")
        End Try
    End Sub

    Private Sub gdvTask_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gdvTask.DoubleClick
        Dim frmTempTask As New frmTask
        LoadCursor(Me)
        With frmTempTask
            .MdiParent = Me.ParentForm
            .RecId = Val(gdvTask.GetRowCellValue(gdvTask.FocusedRowHandle, "record_id"))
            .Show()
            .btnEdit_Click(Nothing, Nothing)
        End With
        DestroyCrushor(Me)
    End Sub

    Private Sub MenuSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuSend.Click
        Dim frmTempMessages As New frmMessages
        LoadCursor(Me)
        With frmTempMessages
            .MdiParent = Me.ParentForm
            .mblnCheck = True
            .mintSenderID = CInt(gdvMessageWaiting.GetRowCellValue(gdvMessageWaiting.FocusedRowHandle, "SenderId"))
            .Show()
        End With
        DestroyCrushor(Me)
    End Sub

    Private Sub MenuDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuDelete.Click
        If gdvMessageWaiting.RowCount > 0 AndAlso MessageBox.Show("Are you sure you want to delete this message?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            Call DeleteFromTable("tblMessages", "MessageId=" & CInt(gdvMessageWaiting.GetRowCellValue(gdvMessageWaiting.FocusedRowHandle, "MessageId")))
            gdvMessageWaiting.DeleteSelectedRows()
        End If
    End Sub

    Private Sub gdvMessageWaiting_RowCountChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdvMessageWaiting.RowCountChanged
        If gdvMessageWaiting.RowCount = 0 Then
            MenuDelete.Enabled = False
        Else
            MenuDelete.Enabled = True
        End If
    End Sub

    Private Sub lkDoctor_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkDoctor.EditValueChanged
        Try
            If IsDBNullOrNothing(lkDoctor.EditValue) Then Exit Sub

            Call PopulateTaskGrid()
            Call PopulatePatientWaitingGrid()
            Dim dsTemp As DataSet
            Dim strDoctorName As String = ""
            Dim strDoctorAddress As String = ""

            dsTemp = FillDataSet("SELECT FirstName, LastName,PhysicianLicenceNumber" & _
                                 " , Address1" & _
                                 " , Address2,Town" & _
                                 " ,Parish,Country" & _
                                 " FROM tblPracticeInfo" & _
                                 " JOIN LtblTown ON tblPracticeInfo.TownId=LtblTown.TownId" & _
                                 " JOIN  LtblParish  ON tblPracticeInfo.ParishId=LtblParish.ParishId" & _
                                 " INNER JOIN tblUsers ON tblPracticeInfo.UserID = tblUsers.UserID" & _
                                 " INNER JOIN LtblCountry ON LtblCountry.CountryId=tblPracticeInfo.CountryId" & _
                                 " WHERE tblPracticeInfo.UserId = " & lkDoctor.EditValue)
            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    strDoctorName = .Rows(0).Item("FirstName") & " " & .Rows(0).Item("LastName")

                    strDoctorAddress = IIf(Trim(.Rows(0).Item("PhysicianLicenceNumber") & "") = "", "", Trim(.Rows(0).Item("PhysicianLicenceNumber") & "") & "," & vbCrLf) & _
                                        IIf(Trim(.Rows(0).Item("Address1") & "") = "", "", Trim(.Rows(0).Item("Address1") & "") & "," & vbCrLf) & _
                                        IIf(Trim(.Rows(0).Item("Address2") & "") = "", "", Trim(.Rows(0).Item("Address2") & "") & "," & vbCrLf) & _
                                        IIf(Trim(.Rows(0).Item("Town") & "") = "", "", Trim(.Rows(0).Item("Town") & "") & ",") & _
                                        IIf(Trim(.Rows(0).Item("Parish") & "") = "", "", Trim(.Rows(0).Item("Parish") & "") & ",") & _
                                        IIf(Trim(.Rows(0).Item("Country") & "") = "", "", Trim(.Rows(0).Item("Country") & ""))
                                      
                    lblUserName.Text = strDoctorName
                    lblUserAddress.Text = strDoctorAddress
                End If

            End With

            'lblName.Text = "Dr. " & dr("FirstName") & " " & dr("LastName")
            'lblAddress.Text = IIf(dr("Address1") = String.Empty, "", dr("Address1") & "," & vbCrLf) & IIf(dr("Address2") = String.Empty, "", dr("Address2") & "," & vbCrLf) & dr("Town") & ", " & dr("Parish") & "," & vbCrLf & dr("Country")

            Call btnRefresh_OpenLink(Nothing, Nothing)
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of mdlAllFunctions")
        End Try
    End Sub

    Private Sub grdPatientWaiting_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles grdPatientWaiting.DoubleClick
        'Open Instance messages form
        'Dim mainForm As New mdiMain

        If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
            ' mainForm.mnuDoctorsNote_ItemClick(Nothing, Nothing)
            Dim frmTempPatientStatus As New frmPatientStatus(PatientStatus.AwaitingDoctor)
            LoadCursor(Me)
            With frmTempPatientStatus
                .MdiParent = Me.ParentForm
                .Show()
            End With
            DestroyCrushor(Me)
        End If

        If gintUserLevelId = 3 Then
            ' mainForm.mnuNursesNote_ItemClick(Nothing, Nothing)
            Dim frmTempPatientStatus As New frmPatientStatus(PatientStatus.AwaitingNurse)
            LoadCursor(Me)
            With frmTempPatientStatus
                .MdiParent = Me.ParentForm
                .Show()
            End With
            DestroyCrushor(Me)
        End If

        If gintUserLevelId = 4 Then
            ' mainForm.mnuChangePatientStatus_ItemClick(Nothing, Nothing)
            Dim frmTempPatientStatus As New frmPatientStatus()
            LoadCursor(Me)
            With frmTempPatientStatus
                .MdiParent = Me.ParentForm
                .Show()
            End With
            DestroyCrushor(Me)
        End If
    End Sub

    Private Sub frmShowAppointment_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
        Me.SendToBack()
    End Sub

    Public Sub btnRefresh_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles btnRefresh.OpenLink
        Call RefreshData("All")
    End Sub

    Private Sub MnuNurseNotes_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MnuNurseNotes.Click

        If Val(Trim(gdvPatientWaiting.GetFocusedRowCellValue("VisitId") & "")) <= 0 Then Exit Sub
        Dim frmTempNurseNote As New frmNurseNote(gdvPatientWaiting.GetFocusedRowCellValue("VisitId"))
        With frmTempNurseNote
            .MdiParent = Me.ParentForm
            .Show()
        End With
    End Sub

    Private Sub MnuDoctorNotes_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MnuDoctorNotes.Click
        If Val(Trim(gdvPatientWaiting.GetFocusedRowCellValue("VisitId") & "")) <= 0 Then Exit Sub
        Dim frmTempDoctorsNote As New frmDoctorsNote
        With frmTempDoctorsNote
            .MdiParent = Me.ParentForm
            .VisitId = gdvPatientWaiting.GetFocusedRowCellValue("VisitId")
            .Show()
        End With
    End Sub

    Private Sub MnuChargesAndPayment_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MnuChargesAndPayment.Click
        If Val(Trim(gdvPatientWaiting.GetFocusedRowCellValue("VisitId") & "")) <= 0 Then Exit Sub
        If isLoaded("frmChargeAndPayment") Then Exit Sub
        Dim frmTempForm As New frmChargeAndPayment(gdvPatientWaiting.GetFocusedRowCellValue("VisitId"), gdvPatientWaiting.GetFocusedRowCellValue("PatientId"), GetPracticeId(gintUserID))
        With frmTempForm
            .Text = gdvPatientWaiting.GetFocusedRowCellValue("Name") & " (" & Now.ToLongDateString & " )"
            .MdiParent = Me.ParentForm
            .Show()
        End With

    End Sub

    Private Function isLoaded(ByVal strFormName As String, Optional ByVal strTag As String = "") As Boolean
        isLoaded = False
        For Each frmchild As Form In Me.ParentForm.MdiChildren
            If Not (frmchild.Tag Is Nothing) Then
                If frmchild.Name.ToString = strFormName And frmchild.Tag.ToString = strTag Then
                    isLoaded = True : frmchild.BringToFront() : Exit Function
                End If
            ElseIf frmchild.Tag Is Nothing Or frmchild.Tag = String.Empty Then
                If frmchild.Name.ToString = strFormName And strTag = String.Empty Then
                    isLoaded = True : frmchild.BringToFront() : Exit Function
                End If
            End If
        Next
    End Function

    Private Sub gdvPatientWaiting_RowCellStyle(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs) Handles gdvPatientWaiting.RowCellStyle
        If Val(gdvPatientWaiting.GetRowCellValue(e.RowHandle, "PatientId")) <= 0 Then Exit Sub
        Dim VisitPatientId As Integer = Val(gdvPatientWaiting.GetRowCellValue(e.RowHandle, "PatientId"))
        Dim apptPatientId As Integer = Val(strRecordID("tblAppointments", "PatientId", "AppointmentDateTime between '" & Format(gdvPatientWaiting.GetRowCellValue(e.RowHandle, "ArrivalTime"), gstrDtFormat & " 00:00") & "' and '" & Format(gdvPatientWaiting.GetRowCellValue(e.RowHandle, "ArrivalTime"), gstrDtFormat & " 23:59") & "' and PatientId=" & VisitPatientId))

        If apptPatientId > 0 Then
            e.Appearance.ForeColor = Color.Red
        End If
    End Sub
End Class